<?php
/**
 * 管理员管理
 * User: cxm
 * Date: 2019/10/24
 * Time: 11:32
 */
namespace App\Http\Controllers\Admin\AdminUser;
use App\Http\Controllers\Admin\Controller;
use App\Models\Admin;
use App\Models\AdminUser;
use App\Models\AdminUserRole;
use Carbon\Carbon;
use DB,Validator;
use Illuminate\Http\Request;

class ManageController extends Controller {
    /**
     * 获取管理员列表
     * URL GET:/admin/manage/get-lists
     * @param Request $request
     * @param string keyword 关键字
     * @param int role_id 角色
     * @param int page 页码
     * @param int limit 每页显示条数
     * @return mixed
     */
    public function getLists(Request $request){
        $params = $request->only(['username','name','role_id','page','limit']);
        $data = AdminUser::getData($params);
        return $this->success('查询成功',$data);
    }

    /**
     * 管理员信息
     * @param Request $request
     * URL POST:/admin/manage/edit
     * @param int admin_id 管理员ID
     * @return mixed
     */
    public function edit(Request $request){
        $params = $request->only(['admin_id']);
        if (!array_key_exists('admin_id',$params) || empty($params['admin_id'])) {
            return $this->error('缺少管理员ID');
        }
        $result = AdminUser::with([
                'file' => function ($query) {
                    $query->select('id','path');
                }
            ])
            ->find($params['admin_id']);
        $result['role_id'] = AdminUserRole::byUserIdGetRoleId($params['admin_id']);
        return $this->success('查询成功',$result);
    }

    /**
     * 管理员添加、编辑处理
     * URL POST:/admin/manage/store
     * @param Request $request
     * @param int id 管理员ID 编辑时传
     * @param string username 登录名称
     * @param string name 昵称
     * @param string phone 手机
     * @param string password 密码
     * @param int avatar 头像
     * @param int role_id 管理员角色
     * @param int sex
     * @return mixed
     * @throws \Exception
     */
    public function store(Request $request){
        $params = $request->only(['id','username','name','phone','password','avatar','role_id','sex']);
        $id = isset($params['id']) ? $params['id'] : 0;
        $validator = Validator::make($params,[
            'username'          => ['required','max:20', 'unique:admin_user,username,' . $id.',id,deleted_at,NULL'],
            'password'          => [$id==0?'required':'','min:6','max:50'],
            'phone'             => ['nullable','regex:/^1\d{10}$/', 'unique:admin_user,phone,' . $id.',id,deleted_at,NULL'],
            'role_id'           => ['required','min:1']
        ],[
            'username.required' => '请输入管理员名称',
            'username.max'      => '名称由1~20位字符组成',
            'username.unique'   => '名称已存在',
            'password.required' => '密码不能为空',
            'password.min'      => '密码由6~50位字符组成',
            'password.max'      => '密码由6~50位字符组成',
            'phone.regex'       => '手机格式错误',
            'phone.unique'      => '手机号已存在',
            'role_id.required'  => '请选择管理员角色',
            'role_id.min'       => '管理员角色错误'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if ($id == 0) {
            $admin_user = new AdminUser();
        }else{
            $admin_user = AdminUser::find($id);
            if (!$admin_user) {
                return $this->error('管理员不存在');
            }
        }
        DB::beginTransaction();
        try{
            $admin_user->username   = $params['username'];
            $admin_user->name       = isset($params['name']) ? $params['name'] : '';
            if (array_key_exists('password',$params) && !empty($params['password'])) {
                $admin_user->password =  bcrypt($params['password']);
            }
            $admin_user->phone      = isset($params['phone']) ? $params['phone'] : '';
            $admin_user->user_type  = 2;
            $admin_user->sex        = isset($params['sex']) ? $params['sex'] : 1;
            $admin_user->avatar     = isset($params['avatar']) ? $params['avatar'] : 0;
            if($admin_user->save()) {
                // 添加权限
                if (AdminUserRole::where('user_id',$admin_user->id)->first()) {
                    AdminUserRole::where('user_id',$admin_user->id)->update(['role_id'=>$params['role_id']]);
                }else{
                    AdminUserRole::insert([
                        'user_id'       => $admin_user->id,
                        'role_id'       => $params['role_id'],
                        'created_at'    => Carbon::now(),
                        'updated_at'    => Carbon::now()
                    ]);
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**
     * 管理员修改角色
     * URL POST:/admin/manage/editRole
     * @param Request $request
     * @param int admin_id 管理员ID
     * @param int role_id 权限ID
     * @return mixed
     */
    public function editRole(Request $request){
        $params = $request->only(['admin_id','role_id']);
        if (!array_key_exists('admin_id',$params) || $params['admin_id'] < 1) {
            return $this->error('缺少管理员ID');
        }
        if (!array_key_exists('role_id',$params) || $params['role_id'] <1) {
            return $this->error('请选择权限');
        }
        $where = [];
        $where[] = ['user_id',$params['admin_id']];
        $field = ['role_id'=>$params['role_id']];
        $data = AdminUserRole::updated($where,$field);
        if (!$data) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    /**
     * 设置状态
     * @return mixed
     */
    public function updateStatus()
    {
        $inputs = request()->only(['id', 'status']);
        // 验证的规则
        $rules = [
            'id' => 'required',
            'status' => 'required|in:1,2',
        ];
        // 自定义错误信息
        $message = [
            'id.required' => ':attribute是必须的',
            'status.required' => ':attribute是必须的',
            'status.in' => ':attribute必须是【启用、禁用】中的值',
        ];
        // 自定义字段姓名
        $customAttrutes = [
            'id' => '参数',
            'status' => '状态',
        ];
        $validator = Validator::make($inputs, $rules, $message, $customAttrutes);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $re = AdminUser::set($inputs);
        if ($re['code'] != 0) {
            return $this->error('设置失败！');
        }
        return $this->success('设置成功！');
    }

    /**
     * 管理员删除
     * URL POST:/admin/manage/delete
     * @param Request $request
     * @param array ids 管理员ID
     * @return mixed
     */
    public function delete(Request $request){
        $params = $request->only(['ids']);
        if (!array_key_exists('ids',$params) || empty($params['ids'])) {
            return $this->error('缺少管理员ID');
        }
        // 查看是否为超级管理员
        $isSuperMan = AdminUser::isSuperMan($params['ids']);
        if ($isSuperMan) {
            return $this->error('里面包含超级管理员，超级管理员不能删除');
        }
        $data = AdminUser::whereIn('id',$params['ids'])->delete();
        if ($data === false) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 重置密码
     * URL POST:/admin/manage/set_pass
     * @param Request $request
     * @param int id 管理员ID
     * @param string password 密码
     * @return mixed
     */
    public function updatePassword(Request $request){
        $params = $request->only(['id', 'password']);
        // 验证的规则
        $rules = [
            'id' => 'required|integer',
            'password' => 'required',
        ];
        // 自定义错误信息
        $message = [
            'id.required' => ':attribute是必须的',
            'id.integer' => ':attribute必须是int型',
            'password.required' => ':attribute是必须的',
        ];
        // 自定义字段姓名
        $customAttrutes = [
            'id' => '参数',
            'password' => '秘密',
        ];
        $validator = Validator::make($params, $rules, $message, $customAttrutes);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $params['password'] = bcrypt($params['password']);
        $re = AdminUser::setPass($params);
        if ($re['code'] != 0) {
            return $this->error('设置失败！');
        }
        return $this->success('设置成功！');
    }
}